/**
 * Created by jiachenpan on 16/11/18.
 */

export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if (('' + time).length === 10) time = parseInt(time) * 1000
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

export function formatTime(time, option) {
  time = +time * 1000
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

export function isExternal(path) {
  return /^(https?:|mailto:|tel:)/.test(path)
}

// obj转url
export function objToUrl (param) {
  if (param === null) return ''
  var tempArr = []
  for (var key in param) {
    if (param.hasOwnProperty(key) && param[key] !== undefined) {
      tempArr.push(key + '=' + param[key])
    }
  }
  return '?' + tempArr.join('&')
}

// url转obj
export function urlToObj (url) {
  if (url === null || url.indexOf('?') < 0) return {}
  var query = location.href.split('?')[1]
  var tempObj = {}
  query.split('&').forEach(function (item) {
    var key = item.split('=')[0]
    tempObj[key] = decodeURI(item.split('=')[1])
  })
  return tempObj
}

/**
 * 获取url中参数
 * @param  {String} query 要获取的参数，对大小写敏感
 * @return {String}       要获取的参数对应的值，为获取则为空字符串
 */
export function getQuery (query) {
  if (!query) return ''
  const _query = window.location.href.split('?')[1]
  if (_query) {
    const _eachQuery = _query.split('&')
    let i = 0
    while (i < _eachQuery.length) {
      let _keyValue = _eachQuery[i].split('=')
      if (_keyValue[0] === query) {
        return _keyValue[1]
      }
      i++
    }
  }
  return ''
}

/**
 * 删除url中参数
 * @param  {String} query 要删除的query
 * @param  {String} url   要删除的url
 * @return {String}       返回删除后的url
 */
export function delQuery (query, url = window.location.href) {
  let urlArr = url.split('?')
  if (urlArr.length > 1 && urlArr[1].indexOf(query) > -1) {
    let _search = urlArr[1]
    let obj = {}
    let arr = _search.split('&')
    for (let i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    }
    delete obj[query]
    const urlte = `${urlArr[0]}?${JSON.stringify(obj).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')}`
    return urlte
  } else {
    return url || window.location.href
  }
}

/**
 * 替换url中query值
 * @param url
 * @param query
 * @param value
 * @returns {string}
 */
export function replaceQuery (url = window.location.href, query, value) {
  let urlArr = url.split('?')
  if (urlArr.length > 1 && urlArr[1].indexOf(query) > -1) {
    let _search = urlArr[1]
    let obj = {}
    let arr = _search.split('&')
    for (let i = 0; i < arr.length; i++) {
      arr[i] = arr[i].split('=')
      obj[arr[i][0]] = arr[i][1]
    }
    obj[query] = encodeURI(value)
    return `${urlArr[0]}?${JSON.stringify(obj).replace(/["{}]/g, '').replace(/:/g, '=').replace(/,/g, '&')}`
  } else {
    return url || window.location.href
  }
}

// 获取query历史值，转换对象判空并返回
export function getPreSubmitData () {
  var queryData = urlToObj(location.href)
  Object.keys(queryData).forEach(item => {
    if (queryData[item] !== 0 && queryData[item] === '') {
      delete this.searchForm[item]
    }
  })
  return queryData
}
